import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Form, Field, Balloon, Button, Checkbox, Tag } from '@teamix/ui';
import { Header, Content, YunxiaoIcon, ButtonIcon, Title } from '@alife/devops-ui';
import ListLoading from 'atComponents/ListLoading';
import { enterPage, Perf } from 'utils/track';
import { navigateOpen } from 'utils/router';
import * as actions from '../actions/index';
import BtnConfirm from './btnConfirm';
import KmsStatusCheckConfirm from './kmsStatusCheckConfirm';
import docs from 'utils/docs';
import isEqual from 'lodash.isequal';
import RepoDialog from 'components/encryptedProjectsDialog';
import intl from '../../../../../../../../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const kms_price_doc = 'https://help.aliyun.com/document_detail/52608.html';
// 区域写死
const location = 'cn-hangzhou';
const location_name = intl.get({
  id: 'code-assets.crypto.containers.root.ChinaHangzhou',
  defaultMessage: '华东1（杭州）',
});
const kms_keys_link = `https://kms.console.aliyun.com/${location}/key/list`;
const get_kms_item_link_fn = (kms_id) => {
  return `https://kms.console.aliyun.com/${location}/key/detail/${kms_id}`;
};
// 加密级别： EncryptNewProject 新仓库默认加密， Default或空 选择开启
const cryptoLevelMap = {
  0: 'Default',
  1: 'EncryptNewProject',
};

// 加密Key状态
const cryptoKeyStatus = {
  active: {
    color: 'blue',
    text: intl.get({
      id: 'code-assets.crypto.containers.root.Activated',
      defaultMessage: '已激活',
    }),
  },

  disable: {
    color: undefined,
    text: intl.get({ id: 'code-assets.crypto.containers.root.Disable', defaultMessage: '禁用' }),
  },

  default: {
    color: undefined,
    text: intl.get({ id: 'code-assets.crypto.containers.root.Disable', defaultMessage: '禁用' }),
  },
};

const kmsHelp = (
  <Balloon
    closable={false}
    trigger={
      <ButtonIcon
        className="kms-help-trigger-icon"
        text
        name="information-line"
        style={{ marginLeft: 4, marginBottom: 4, display: 'inline-block' }}
      />
    }
    align="t"
    popupContainer={(trigger) => trigger.parentNode}
  >
    {intl.get({
      id: 'code-assets.crypto.containers.root.TheKmsKeyFunctionCharges',
      defaultMessage: '使用KMS密钥功能会产生少量密钥API调用费用，详情参考',
    })}
    <a href={kms_price_doc} target="_blank" rel="noreferrer">
      {intl.get({
        id: 'code-assets.crypto.containers.root.KmsBillingStandard',
        defaultMessage: 'KMS计费标准',
      })}
    </a>
  </Balloon>
);

const ticket = (
  <Balloon.Tooltip
    trigger={
      <a href={docs('submit-work-order')} target="_blank" rel="noreferrer">
        {intl.get({
          id: 'code-assets.crypto.containers.root.ApplyForATicket',
          defaultMessage: '工单申请使用',
        })}
      </a>
    }
    align="t"
    popupContainer={(trigger) => trigger.parentNode}
  >
    {intl.get({
      id: 'code-assets.crypto.containers.root.AdvancedFeaturesInTheInternal',
      defaultMessage: '高级功能内测中，支持提交工单申请使用',
    })}
  </Balloon.Tooltip>
);

class Root extends Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
  }

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.crypto.containers.root.WarehouseEncryptionCloudEffectCodeup',
      defaultMessage: '仓库加密 · 云效 Codeup',
    });
    this.props.getCryptoInfo();

    enterPage('Organization-Settings-Backup', {
      sendPerf: false,
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.formInitData && nextProps.formInitData !== this.props.formInitData) {
      this.field.setValues({
        name: nextProps.formInitData.name || '',
        location: nextProps.formInitData.location || '',
      });
    }
  }

  getIsFormNotChanged = () => {
    const { formInitData } = this.props;
    const formData = this.field.getValues();
    return isEqual(formData, formInitData);
  };

  componentWillUnmount() {
    this.props.resetData();
  }

  openOssAuthPage = () => {
    const { isAuthorizing } = this.props;
    if (isAuthorizing) {
      return;
    }
    const { authorization_link, authorization_role } = this.props.cryptoInfo || {};
    const openedWindow = navigateOpen(authorization_link);
    const windowChecker = setInterval(() => {
      if (openedWindow.location.pathname === '/oauth/aliyun/success') {
        window.clearInterval(windowChecker);
        this.props.cryptoAuthorize(authorization_role);
        if (!openedWindow.closed) {
          openedWindow.close();
        }
      }
    }, 500);
  };

  renderKeys = (isCurrentUser) => {
    const { cryptoInfo, keys, isLoadingKeys } = this.props;
    if (!cryptoInfo.service_authorization_id) {
      return null;
    }
    if (isLoadingKeys) {
      return <ListLoading />;
    }
    // 当前数据只会有一个,没有则写默认值
    const hasKey = keys && keys[0];
    const count = hasKey ? keys[0].projects_count : 0;
    const alias_name =
      hasKey && keys[0] && keys[0].cmk && keys[0].cmk.alias_names ? keys[0].cmk.alias_names[0] : '';
    const key_name = hasKey ? alias_name || keys[0].cmk_id : '';
    const condition_status = hasKey && keys[0] && keys[0].cmk ? keys[0].cmk.condition_status : '';
    return (
      <div className="crypto-key-list">
        <div className="crypto-key-item">
          <div className="crypto-key-item-title">
            <div className="crypto-key-item-label">
              {intl.get({
                id: 'code-assets.crypto.containers.root.ServiceKey',
                defaultMessage: '服务密钥：',
              })}
            </div>
            <div className="crypto-key-item-value">
              <div className="crypto-key-img">
                <YunxiaoIcon type="authority-line" />
              </div>
              <div className={`crypto-key-id ${hasKey ? '' : 'gray'}`}>
                {key_name ? (
                  <a
                    href={get_kms_item_link_fn(keys[0].cmk_id)}
                    target="_blank"
                    onClick={(e) => {
                      if (!isCurrentUser) {
                        e.preventDefault();
                      }
                    }}
                    rel="noreferrer"
                  >
                    {key_name}
                  </a>
                ) : (
                  intl.get({
                    id: 'code-assets.crypto.containers.root.ToBeGeneratedTheKey',
                    defaultMessage: '待生成（仓库执行加密时将自动生成密钥）',
                  })
                )}
              </div>
              {hasKey && (
                <Tag
                  color={cryptoKeyStatus[condition_status || 'default'].color}
                  className="crypto-key-tag"
                >
                  {cryptoKeyStatus[condition_status || 'default'].text}
                </Tag>
              )}
            </div>
          </div>
          <div className="crypto-key-item-count">
            <div className="crypto-key-item-label">
              {intl.get({
                id: 'code-assets.crypto.containers.root.EffectiveRepository',
                defaultMessage: '生效仓库：',
              })}
            </div>
            <div className="crypto-key-item-value">
              <span className="count">
                {count || 0}
                {intl.get({ id: 'code-assets.crypto.containers.root.A', defaultMessage: '个' })}
              </span>
              {count > 0 && (
                <RepoDialog
                  keyId={keys[0].id}
                  trigger={
                    <Button type="primary" text>
                      {intl.get({
                        id: 'code-assets.crypto.containers.root.See',
                        defaultMessage: '查看',
                      })}
                    </Button>
                  }
                />
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  getKmsStatusInfo = (kms_status) => {
    let color = '';
    let status;
    if (!kms_status) {
      status = '';
    } else if (kms_status.enabled) {
      status = intl.get({
        id: 'code-assets.crypto.containers.root.Normal',
        defaultMessage: '正常',
      });
    } else if (kms_status.in_debt_overdue) {
      status = intl.get({
        id: 'code-assets.crypto.containers.root.OverduePayment',
        defaultMessage: '已欠费超期',
      });
      color = 'danger';
    } else if (kms_status.in_debt) {
      status = intl.get({
        id: 'code-assets.crypto.containers.root.OverduePayment.1',
        defaultMessage: '已欠费',
      });
      color = 'danger';
    } else {
      status = '';
    }

    return {
      color,
      status,
    };
  };

  render() {
    const { isLoading, cryptoInfo, keys, isLoadingKeys, needRetryAuth } = this.props;

    const {
      service_authorization_id,
      authorized_by,
      authorized_account,
      crypto_level,
      project_settings_enabled,
      kms_status,
      is_crypto_enabled,
    } = cryptoInfo;
    // 有密钥被使用，不可取消授权
    const isRemoveAuthDisabled =
      isLoadingKeys ||
      keys.some((key) => {
        return key.projects_count > 0;
      });
    // 企业用户名
    const ownerName = (authorized_by && authorized_by.name) || authorized_account;
    // 授权用户是当前用户，显示前往 KMS 页面
    const isCurrentUser =
      window.FORCE.user &&
      authorized_by &&
      Number(window.FORCE.user.codeUserId) === authorized_by.id;
    const { status: kms_status_str, color: kms_status_color } = this.getKmsStatusInfo(kms_status);

    return (
      <>
        <Header
          title={
            <div>
              {intl.get({
                id: 'code-assets.crypto.containers.root.RepositoryEncryption',
                defaultMessage: '仓库加密',
              })}

              <Balloon
                closable={false}
                trigger={
                  <ButtonIcon
                    text
                    name="question-line"
                    style={{
                      marginLeft: 4,
                      display: 'inline-block',
                      position: 'relative',
                      top: '-1px',
                    }}
                  />
                }
                align="t"
              >
                <a href={docs('crypto')} target="_blank" rel="noreferrer">
                  {intl.get({
                    id: 'code-assets.crypto.containers.root.WhatIsWarehouseEncryption',
                    defaultMessage: '什么是仓库加密？',
                  })}
                </a>
              </Balloon>
            </div>
          }
        />

        <Content>
          {isLoading ? (
            <ListLoading />
          ) : (
            <div className="crypto-form">
              <div className="crypto-item">
                <div className="crypto-item-left">
                  <div className="crypto-item-title">
                    {intl.get({
                      id: 'code-assets.crypto.containers.root.AllowRepositoryEncryption',
                      defaultMessage: '允许使用仓库加密',
                    })}
                  </div>
                  {!service_authorization_id ? (
                    <div className="crypto-item-desc">
                      {intl.get({
                        id: 'code-assets.crypto.containers.root.SupportsAutomaticEncryptionOfCode',
                        defaultMessage:
                          '支持对代码库数据自动加密，需使用阿里云密钥管理服务 ( KMS )，建议使用',
                      })}
                      <span className="strong">
                        {intl.get({
                          id: 'code-assets.crypto.containers.root.EnterprisePublicAccount',
                          defaultMessage: '企业公共账号',
                        })}
                      </span>
                      {intl.get({
                        id: 'code-assets.crypto.containers.root.AuthorizationToAvoidKeyReplacement',
                        defaultMessage: '授权，避免因授权人频繁变更导致的密钥更换问题',
                      })}{' '}
                      {is_crypto_enabled ? (
                        <KmsStatusCheckConfirm
                          trigger={
                            <a className="no-href-with-click">
                              {intl.get({
                                id: 'code-assets.crypto.containers.root.AuthorizeKms',
                                defaultMessage: '授权 KMS 服务',
                              })}
                            </a>
                          }
                          onClick={this.openOssAuthPage}
                        />
                      ) : (
                        ticket
                      )}
                      {is_crypto_enabled && kmsHelp}
                    </div>
                  ) : (
                    <div className="crypto-item-detail">
                      <div className="crypto-item-detail-left flex">
                        <div className="crypto-base-info strong">
                          <span className="crypto-base-info-label">
                            {intl.get({
                              id: 'code-assets.crypto.containers.root.EncryptionMethod',
                              defaultMessage: '加密方式：',
                            })}
                          </span>
                          <div className="crypto-base-info-value kms-options">
                            <span>KMS</span>
                            {kmsHelp}
                          </div>
                        </div>
                        <div className="crypto-base-info">
                          <span className="crypto-base-info-label">
                            {intl.get({
                              id: 'code-assets.crypto.containers.root.Authorizer',
                              defaultMessage: '授权人：',
                            })}
                          </span>
                          <span className="crypto-base-info-value">
                            <div className="backup-item-detail-left-owner">
                              <Title align="t" trigger={<span>{ownerName}</span>}>
                                {ownerName}
                              </Title>
                            </div>
                          </span>
                        </div>
                        <div className="crypto-base-info">
                          <span className="crypto-base-info-label">
                            {intl.get({
                              id: 'code-assets.crypto.containers.root.Region',
                              defaultMessage: '地域：',
                            })}
                          </span>
                          <span className="crypto-base-info-value">{location_name}</span>
                        </div>
                        {kms_status_str && (
                          <div className="crypto-base-info kms-status">
                            <span className="crypto-base-info-label">
                              {intl.get({
                                id: 'code-assets.crypto.containers.root.KmsServiceStatus',
                                defaultMessage: 'KMS 服务状态：',
                              })}
                            </span>
                            <span className={`crypto-base-info-value ${kms_status_color}`}>
                              {kms_status_str}
                            </span>
                          </div>
                        )}
                      </div>
                      <div className="crypto-item-detail-right">
                        {isCurrentUser && (
                          <Button
                            text
                            type="primary"
                            className="go-btn"
                            component="a"
                            href={kms_keys_link}
                            target="_blank"
                          >
                            {intl.get({
                              id: 'code-assets.crypto.containers.root.GoToKms',
                              defaultMessage: '前往 KMS',
                            })}
                          </Button>
                        )}

                        {/* 有加密被使用，禁止解除授权 */}
                        {/* 如果用户删除ram里的角色，需要重新授权 */}
                        {needRetryAuth && isCurrentUser ? (
                          <KmsStatusCheckConfirm
                            trigger={
                              <a className="no-href-with-click ml12">
                                {intl.get({
                                  id: 'code-assets.crypto.containers.root.ReAuthorize',
                                  defaultMessage: '重新授权',
                                })}
                              </a>
                            }
                            onClick={this.openOssAuthPage}
                          />
                        ) : (
                          <BtnConfirm
                            trigger={
                              <Button
                                text
                                type="normal"
                                className={`relieve-btn ${isRemoveAuthDisabled ? 'pending' : ''}`}
                                disabled={isRemoveAuthDisabled}
                              >
                                {intl.get({
                                  id: 'code-assets.crypto.containers.root.RevokeAuthorization',
                                  defaultMessage: '解除授权',
                                })}
                              </Button>
                            }
                            isRemoveAuthDisabled={isRemoveAuthDisabled}
                            disabledHelp={
                              isLoadingKeys ? (
                                ''
                              ) : (
                                <div>
                                  {intl.get({
                                    id: 'code-assets.crypto.containers.root.TheServiceKeyHasBeen',
                                    defaultMessage:
                                      '服务密钥已被使用，需生效仓库全部解密后执行解除授权操作',
                                  })}
                                  &nbsp;&nbsp;
                                  <a href={docs('crypto')} target="_blank" rel="noreferrer">
                                    {intl.get({
                                      id: 'code-assets.crypto.containers.root.HowToDecrypt',
                                      defaultMessage: '如何解密',
                                    })}
                                  </a>
                                </div>
                              )
                            }
                            onClick={() => {
                              if (isRemoveAuthDisabled) {
                                return;
                              }
                              this.props.removeBackupAuth(service_authorization_id);
                            }}
                            needPopConfirm={!isRemoveAuthDisabled}
                          />
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>
              {service_authorization_id && (
                <div>
                  <Form
                    labelAlign="left"
                    size="small"
                    field={this.field}
                    className="crypto-setting-form"
                  >
                    {/* 新建仓库默认开启加密 暂时隐藏 */}
                    <FormItem label="" {...formItemLayout}>
                      <Checkbox
                        checked={crypto_level === cryptoLevelMap[1]}
                        onChange={(value) => {
                          this.props.updateCryptoInfo({
                            crypto_level: value ? cryptoLevelMap[1] : cryptoLevelMap[0],
                            project_settings_enabled,
                          });
                        }}
                      >
                        {intl.get({
                          id: 'code-assets.crypto.containers.root.EncryptionIsEnabledByDefault',
                          defaultMessage: '新建仓库默认开启加密',
                        })}
                      </Checkbox>
                    </FormItem>
                    <FormItem label="" {...formItemLayout}>
                      <Checkbox
                        checked={project_settings_enabled}
                        onChange={(value) => {
                          this.props.updateCryptoInfo({
                            crypto_level,
                            project_settings_enabled: value,
                          });
                        }}
                      >
                        {intl.get({
                          id: 'code-assets.crypto.containers.root.AllowsTheRepositoryAdministratorTo',
                          defaultMessage: '允许仓库管理员修改加密设置',
                        })}
                      </Checkbox>
                    </FormItem>
                  </Form>
                </div>
              )}

              {this.renderKeys(isCurrentUser)}
              <Perf page="Organization-Settings-Backup" />
            </div>
          )}
        </Content>
      </>
    );
  }
}

export default connect(
  (state) => state.organization.settings.crypto,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
